<template>
  <div class="scores-container">
    <el-card class="scores-card">
      <template #header>
        <div class="card-header">
          <h3>我的体测成绩</h3>
          <div class="header-actions">
            <el-input v-model="searchText" placeholder="搜索项目名称" prefix-icon="el-icon-search" clearable @clear="handleSearch" style="width: 220px" />
          </div>
        </div>
      </template>

      <!-- 成绩概览 -->
      <div class="score-overview" v-if="!loading && scores.length > 0">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-card shadow="hover" class="overview-card total-card">
              <div class="overview-content">
                <div class="overview-icon">
                  <el-icon>
                    <DataLine />
                  </el-icon>
                </div>
                <div class="overview-info">
                  <div class="overview-title">总测试项目</div>
                  <div class="overview-value">{{ scores.length }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="hover" class="overview-card pass-card">
              <div class="overview-content">
                <div class="overview-icon">
                  <el-icon>
                    <CircleCheckFilled />
                  </el-icon>
                </div>
                <div class="overview-info">
                  <div class="overview-title">合格项目</div>
                  <div class="overview-value">{{ passCount }}</div>
                </div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="8">
            <el-card shadow="hover" class="overview-card rate-card">
              <div class="overview-content">
                <div class="overview-icon">
                  <el-icon>
                    <DataAnalysis />
                  </el-icon>
                </div>
                <div class="overview-info">
                  <div class="overview-title">合格率</div>
                  <div class="overview-value">{{ passRate }}%</div>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 成绩列表 -->
      <el-table :data="filteredScores" style="width: 100%; margin-top: 20px;" border v-loading="loading" :default-sort="{ prop: 'sportItem.itemName', order: 'ascending' }">
        <el-table-column prop="sportItem.itemName" label="项目名称" min-width="150" align="center" sortable />
        <el-table-column label="成绩" align="center">
          <template #default="{ row }">
            <template v-if="row.isPass === -1">
              --
            </template>
            <template v-else-if="isRunningItem(row.sportItem)">
              {{ formatRunningTime(row.storageValue) }}
            </template>
            <template v-else>
              {{ row.storageValue }} {{ row.sportItem?.unit }}
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="isPass" label="是否合格" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row)" effect="dark" size="small">
              {{ getStatusText(row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="达标标准" align="center">
          <template #default="{ row }">
            <template v-if="isRunningItem(row.sportItem)">
              ≤ {{ formatRunningTime(getPassValue(row)) }}
            </template>
            <template v-else>
              ≥ {{ getPassValue(row) }} {{ row.sportItem?.unit }}
            </template>
          </template>
        </el-table-column>
        <el-table-column label="详情" width="80" align="center">
          <template #default="{ row }">
            <el-button type="primary" size="small" text @click="showDetail(row)">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空数据提示 -->
      <el-empty v-if="!loading && scores.length === 0" description="暂无成绩数据" style="margin-top: 40px;" />
    </el-card>

    <!-- 成绩详情对话框 -->
    <el-dialog v-model="detailVisible" title="成绩详情" width="500px" destroy-on-close>
      <div v-if="currentScore" class="score-detail">
        <div class="detail-item detail-title">
          <h3>{{ currentScore.sportItem?.itemName }}</h3>
        </div>

        <div class="detail-item">
          <span class="detail-label">您的成绩：</span>
          <span class="detail-value highlight" v-if="currentScore.isPass !== -1">
            <template v-if="isRunningItem(currentScore.sportItem)">
              {{ formatRunningTime(currentScore.storageValue) }}
            </template>
            <template v-else>
              {{ currentScore.storageValue }} {{ currentScore.sportItem?.unit }}
            </template>
          </span>
          <span class="detail-value" v-else>暂未测试</span>
        </div>

        <div class="detail-item">
          <span class="detail-label">达标标准：</span>
          <span class="detail-value">
            <template v-if="isRunningItem(currentScore.sportItem)">
              ≤ {{ formatRunningTime(getPassValue(currentScore)) }}
            </template>
            <template v-else>
              ≥ {{ getPassValue(currentScore) }} {{ currentScore.sportItem?.unit }}
            </template>
          </span>
        </div>

        <div class="detail-item">
          <span class="detail-label">是否合格：</span>
          <el-tag :type="getStatusType(currentScore)" effect="dark">
            {{ getStatusText(currentScore) }}
          </el-tag>
        </div>

        <div class="detail-item">
          <span class="detail-label">适用性别：</span>
          <span class="detail-value">{{ currentScore.sportItem?.genderScope }}</span>
        </div>

        <div class="detail-item result-feedback" v-if="currentScore.isPass !== -1">
          <span class="detail-label">结果分析：</span>
          <div class="feedback-content">
            <p v-if="currentScore.isPass === 1">
              恭喜你已经达到了标准！继续保持这种良好的状态，你会更优秀！
            </p>
            <p v-else>
              距离达标还有一定差距，建议加强锻炼，相信你下次一定能够达标！
            </p>
          </div>
        </div>

        <div class="detail-item result-feedback" v-else>
          <span class="detail-label">提示：</span>
          <div class="feedback-content">
            <p>该项目尚未测试，请等待体测安排或联系体育教师。</p>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { DataLine, CircleCheckFilled, DataAnalysis } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getStudentScores } from '@/api/score'
import { getSportItems } from '@/api/sportItem'
import { getUserInfo } from '@/utils/auth'

// 状态变量
const loading = ref(false)
const scores = ref([])
const sportItems = ref([])
const searchText = ref('')
const detailVisible = ref(false)
const currentScore = ref(null)
const userInfo = ref(null)

// 初始化用户信息
onMounted(() => {
  userInfo.value = getUserInfo()
})

// 计算属性：获取适用于当前学生性别的所有体测项目
const applicableSportItems = computed(() => {
  if (!userInfo.value || !userInfo.value.gender) return []

  return sportItems.value.filter(item =>
    item.genderScope === '通用' || item.genderScope === userInfo.value.gender
  )
})

// 计算属性：合并所有项目和成绩数据
const allProjectsWithScores = computed(() => {
  // 如果没有加载到项目或成绩，返回空数组
  if (applicableSportItems.value.length === 0) return []

  // 创建一个包含所有适用项目的数组
  return applicableSportItems.value.map(item => {
    // 查找该项目是否有成绩记录
    const existingScore = scores.value.find(score => score.itemId === item.id)

    if (existingScore) {
      // 如果有成绩记录，直接使用
      return existingScore
    } else {
      // 如果没有成绩记录，创建一个"未测试"的项目
      return {
        itemId: item.id,
        sportItem: item,
        storageValue: null,
        isPass: -1, // 使用-1表示未测试
        id: null,
        stuId: userInfo.value?.stuId,
        status: 'untested' // 添加状态标记
      }
    }
  })
})

// 计算属性：过滤后的成绩列表
const filteredScores = computed(() => {
  if (!searchText.value) {
    return allProjectsWithScores.value
  }

  return allProjectsWithScores.value.filter(score => {
    return score.sportItem && score.sportItem.itemName.includes(searchText.value)
  })
})

// 更新现有的计算属性
const passCount = computed(() => {
  return scores.value.filter(score => score.isPass === 1).length
})

const passRate = computed(() => {
  if (scores.value.length === 0) return 0
  return Math.round((passCount.value / scores.value.length) * 100)
})

// 生命周期方法
onMounted(async () => {
  loading.value = true
  try {
    // 获取用户信息
    userInfo.value = getUserInfo()

    // 获取所有体测项目
    await fetchSportItems()

    // 获取学生成绩
    await fetchScores()
  } catch (error) {
    console.error('加载成绩数据失败:', error)
    ElMessage.error('加载成绩数据失败，请刷新重试')
  } finally {
    loading.value = false
  }
})

// 方法
async function fetchScores() {
  try {
    const res = await getStudentScores()
    if (res.code === 200) {
      scores.value = res.data || []
    } else {
      console.error('获取成绩失败:', res.message)
    }
  } catch (error) {
    console.error('获取成绩失败:', error)
  }
}

function handleSearch() {
  // 搜索处理，当前已通过计算属性实现
}

function isRunningItem(sportItem) {
  return sportItem &&
    sportItem.unit === '秒' &&
    (sportItem.itemName.includes('米跑') || sportItem.itemName.includes('跑步'))
}

function formatRunningTime(totalSeconds) {
  if (totalSeconds === null || totalSeconds === undefined) return '-'

  // 特殊处理短跑项目（如50米跑），直接显示秒数
  if (totalSeconds < 60) {
    return `${totalSeconds.toFixed(1)}秒`
  }

  // 长跑项目（如1000米跑、800米跑）显示为分:秒格式
  const minutes = Math.floor(totalSeconds / 60)
  const seconds = Math.floor(totalSeconds % 60)
  const decimalPart = totalSeconds % 1 ? (totalSeconds % 1).toFixed(1).substring(1) : ''

  return `${minutes}分${seconds.toString().padStart(2, '0')}${decimalPart}秒`
}

function getPassValue(score) {
  if (!score || !score.sportItem) return '-'

  if (score.sportItem.genderScope === '通用') {
    return score.student?.gender === '男' ? score.sportItem.malePass : score.sportItem.femalePass
  } else if (score.sportItem.genderScope === '男') {
    return score.sportItem.malePass
  } else if (score.sportItem.genderScope === '女') {
    return score.sportItem.femalePass
  }

  return '-'
}

function showDetail(score) {
  currentScore.value = score
  detailVisible.value = true
}

// 获取成绩状态文本
function getStatusText(score) {
  if (!score || score.isPass === -1) return '未测试'
  return score.isPass === 1 ? '合格' : '不合格'
}

// 获取成绩状态类型
function getStatusType(score) {
  if (!score || score.isPass === -1) return 'info' // 未测试显示为灰色
  return score.isPass === 1 ? 'success' : 'danger'
}

// 获取所有体测项目数据
async function fetchSportItems() {
  try {
    const res = await getSportItems()
    if (res.code === 200) {
      sportItems.value = res.data || []
    } else {
      console.error('获取体测项目失败:', res.message)
    }
  } catch (error) {
    console.error('获取体测项目失败:', error)
  }
}
</script>

<style scoped>
.scores-container {
  padding: 20px;
}

.scores-card {
  min-height: calc(100vh - 120px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.score-overview {
  margin-bottom: 20px;
}

.overview-card {
  height: 100px;
  margin-bottom: 20px;
}

.overview-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.overview-icon {
  font-size: 32px;
  padding: 0 20px;
}

.overview-info {
  display: flex;
  flex-direction: column;
}

.overview-title {
  font-size: 16px;
  color: #606266;
}

.overview-value {
  font-size: 28px;
  font-weight: bold;
  margin-top: 10px;
}

.total-card .overview-icon {
  color: #409EFF;
}

.pass-card .overview-icon {
  color: #67C23A;
}

.rate-card .overview-icon {
  color: #F56C6C;
}

.score-detail {
  padding: 0 20px;
}

.detail-item {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.detail-title {
  justify-content: center;
  margin-bottom: 30px;
}

.detail-title h3 {
  font-size: 20px;
  margin: 0;
  text-align: center;
}

.detail-label {
  min-width: 80px;
  font-weight: bold;
  color: #606266;
}

.highlight {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}

.result-feedback {
  align-items: flex-start;
}

.feedback-content {
  flex: 1;
  background-color: #F8F8F8;
  padding: 10px;
  border-radius: 4px;
}

.feedback-content p {
  margin: 0;
  line-height: 1.5;
}
</style>